/*
 * Project Name spring-boot-tools
 * File Name SocketClient
 * Package Name com.huxiaosu.tools.cmpp.lib
 * Create Time 2024/5/19
 * Create by name：liujie
 */
package com.huxiaosu.tools.cmpp.lib;

import com.huxiaosu.tools.cmpp.action.MessageHandler;
import com.huxiaosu.tools.cmpp.codec.CodecFactory;
import com.huxiaosu.tools.cmpp.config.CmppClientConfig;
import lombok.extern.slf4j.Slf4j;
import org.apache.mina.core.future.ConnectFuture;
import org.apache.mina.core.future.WriteFuture;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.logging.LoggingFilter;
import org.apache.mina.transport.socket.nio.NioSocketConnector;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.net.InetSocketAddress;

/**
 * Description
 *
 * @author liujie
 * @date 2024/5/19 9:49
 */
@Slf4j
public class SocketClient {

    private static SocketClient instance;

    private IoSession serverSession;

    private NioSocketConnector connector;
    private CmppClientConfig cmppClientConfig;

    public synchronized static SocketClient getInstance(CmppClientConfig cmppClientConfig) {
        if (instance == null) {
            instance = new SocketClient(cmppClientConfig);
        }
        return instance;
    }

    public SocketClient(CmppClientConfig cmppClientConfig) {
        this.cmppClientConfig = cmppClientConfig;
        connPushServer(cmppClientConfig);
    }

    public void connPushServer(CmppClientConfig cmppClientConfig) {
        try {
            // 创建客户端连接器.
            // NioSocketConnector connector = new NioSocketConnector();
            connector = new NioSocketConnector();
            connector.getFilterChain().addLast("logger", new LoggingFilter());
            connector.getFilterChain().addLast("codec", new ProtocolCodecFilter(new CodecFactory("UTF-8")));

            // 设置连接超时检查时间
            connector.setConnectTimeoutCheckInterval(30);
            connector.setHandler(new MessageHandler());

            // 建立连接
            log.info("connection server ip={},port = {}", cmppClientConfig.getSpIp(), cmppClientConfig.getPort());
            ConnectFuture cf = connector
                .connect(new InetSocketAddress(cmppClientConfig.getSpIp(), cmppClientConfig.getPort()));
            // 等待连接创建完成
            cf.awaitUninterruptibly();
            serverSession = cf.getSession();
        }
        catch (Exception e) {
            log.error("connection server error {}", e.getMessage());
            closeSession();
        }
    }

    public void closeSession() {
        serverSession.closeNow();
        serverSession = null;
        connector.dispose(true);
    }
    public void sendMessage(byte[] data){
        try {
            if (serverSession == null) {
                connPushServer(this.cmppClientConfig);
            }
            WriteFuture write = serverSession.write(data);
            boolean done = write.isDone();
            if(done){
                log.info("check success ");
            }
        } catch (Exception e) {
            log.error("sendMessage error {}", e.getMessage());
//			closeSession();
        }
    }
}
